package com.gy.bearhelps.setting;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.gy.bearhelps.R;
import com.gy.bearhelps.base.BaseActivity;
import com.gy.bearhelps.base.BaseBean;
import com.gy.bearhelps.base.WebViewActivity;
import com.gy.bearhelps.setting.adapter.MessageAdapter;
import com.gy.bearhelps.setting.bean.MessageBean;
import com.gy.bearhelps.setting.util.DialogUtil;
import com.gy.bearhelps.util.AnimUtil;
import com.gy.bearhelps.util.ListViewItemListener;
import com.gy.bearhelps.util.RequestResultListener;
import com.gy.bearhelps.util.SharedPrefUtil;
import com.gy.bearhelps.util.Urls;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：gy on 16/11/5
 * 说明：消息列表
 */
public class MessageListActivity extends BaseActivity implements ListViewItemListener{

    private LinearLayout llEmpty;
    private PullToRefreshListView refreshListView;
    private MessageAdapter adapter;
    private List<MessageBean> mLists,requestList;
    private int pageSize,pageStart;
    private String deleteMessage;
    private List<Integer> deletes;

    @Override
    protected void initView() {
        setContentViewRes(R.layout.activity_message_list);
        setTitleMsg("消息列表");
        llEmpty = (LinearLayout) findViewById(R.id.fg_message_empty);
        refreshListView = (PullToRefreshListView) findViewById(R.id.activity_message_listview);
    }

    @Override
    protected void initData() {
        mLists = new ArrayList<>();
        requestList = new ArrayList<>();
        deletes = new ArrayList<>();
        adapter = new MessageAdapter(this,mLists);
        llEmpty.setVisibility(View.GONE);
        deleteMessage = SharedPrefUtil.get("delete_push","");
        if(!TextUtils.isEmpty(deleteMessage)){
            String[] strs = deleteMessage.split(",");
            for (String str : strs){
                deletes.add(Integer.valueOf(str));
            }
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageStart = 0;
                showLoadDialog();
                getList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            }
        });
        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if(!isLoading && requestList.size() >= 15){
                    isLoading = true;
                    pageStart++;
                    getList();
                }
                finishHandler.sendEmptyMessageDelayed(0,200);
            }
        });
        refreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MessageListActivity.this, WebViewActivity.class);
                intent.putExtra(WebViewActivity.URL,mLists.get(position - 1).content);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(MessageListActivity.this);
            }
        });
        refreshListView.getRefreshableView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                DialogUtil.showSelectShopcarDialog(mContext, (position - 1), MessageListActivity.this);
                return false;
            }
        });
    }

    @Override
    protected void fillData() {
        super.fillData();
        refreshListView.setAdapter(adapter);
        getList();
    }

    private void getList(){
        showLoadDialog();
        RequestParams params = new RequestParams(Urls.push_list);
        params.addQueryStringParameter("pageSize","100000");
        params.addQueryStringParameter("pageStart",pageStart+"");
        getRequest(params, new RequestResultListener() {
            @Override
            public boolean onSuccess(BaseBean result) {
                finishHandler.sendEmptyMessageDelayed(0,200);
                try {
                    JSONArray array = new JSONArray(result.data);
                    JSONObject obj = array.getJSONObject(0);
                    Type type = new TypeToken<List<MessageBean>>(){}.getType();
                    requestList = gson.fromJson(obj.optString("list"),type);
                    mLists.clear();
                    if(requestList.size() > 0){
                        for(MessageBean bean : requestList){
                            if(deletes.contains(bean.id)){
                                continue;
                            } else {
                                mLists.add(bean);
                            }
                        }
                    }
                    adapter.notifyDataSetChanged();
                    if(mLists.size() == 0){
                        llEmpty.setVisibility(View.VISIBLE);
                        refreshListView.setVisibility(View.GONE);
                    } else {
                        llEmpty.setVisibility(View.GONE);
                        refreshListView.setVisibility(View.VISIBLE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                finishHandler.sendEmptyMessageDelayed(0,200);
            }
        });
    }

    private Handler finishHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            refreshListView.onRefreshComplete();
        }
    };

    @Override
    public void doPassActionListener(Object obj, int org1, int org2, String str) {
        switch (org1){
            case 0:
                if(TextUtils.isEmpty(deleteMessage)){
                    deleteMessage = mLists.get(org2).id+"";
                } else {
                    deleteMessage = deleteMessage + ","+mLists.get(org2).id;
                }
                SharedPrefUtil.put("delete_push",deleteMessage);
                mLists.remove(org2);
                adapter.notifyDataSetChanged();
                break;
        }
    }
}
